/*
 *
 * Author: Bob Wei
 * Date:   2009/06/15
 * License:free
 * email:  bob61016@gmail.com
 *
 */
// Update a particular HTML element with a new value
function updateHTML(elmId, value){
    document.getElementById(elmId).innerHTML = value;
}

// This function is called when an error is thrown by the player
function onPlayerError(errorCode){
    alert("An error occured of type:" + errorCode);
}

// This function is called when the player changes state
function onPlayerStateChange(newState){
    updateHTML("playerState", newState);
    if (newState == 0) {
        currentURL++;
        var inputURL = $("#url" + currentURL).val();
        if (inputURL) {
            videoID = getVideoIdByURL(inputURL);
            setInterval(ytplayer.loadVideoById(videoID, 0), 1000);
        }
        else {
            currentURL = 1;
            ytPlay();
        }
    }
    else 
        if (newState == 3) 
            updateHTML("videoStatus", "Now Loading...");
        else 
            if (newState == 1) 
                updateHTML("videoStatus", "Playing");
}

// Display information about the current state of the player
function updatePlayerInfo(){
    // Also check that at least one function exists since when IE unloads the
    // page, it will destroy the SWF before clearing the interval.
    if (ytplayer && ytplayer.getDuration) {
        updateHTML("videoDuration", ytplayer.getDuration());
        updateHTML("videoCurrentTime", ytplayer.getCurrentTime());
        updateHTML("bytesTotal", ytplayer.getVideoBytesTotal());
        updateHTML("startBytes", ytplayer.getVideoStartBytes());
        updateHTML("bytesLoaded", ytplayer.getVideoBytesLoaded());
    }
}

// This function is automatically called by the player once it loads
function onYouTubePlayerReady(playerId){
    ytplayer = document.getElementById("ytPlayer");
    // This causes the updatePlayerInfo function to be called every 250ms to
    // get fresh data from the player
    setInterval(updatePlayerInfo, 250);
    updatePlayerInfo();
    ytplayer.addEventListener("onStateChange", "onPlayerStateChange");
    ytplayer.addEventListener("onError", "onPlayerError");
}

// The "main method" of this sample. Called when someone clicks "Run".
var finished = false;
var videoID = "ylLzyHk54Z0";
var currentURL = 1;
var db;

function loadPlayer(){

    // Lets Flash from another domain call JavaScript
    var params = {
        allowScriptAccess: "always"
    };
    // The element id of the Flash embed
    var atts = {
        id: "ytPlayer"
    };
    // All of the magic handled by SWFObject (http://code.google.com/p/swfobject/)
    swfobject.embedSWF("http://www.youtube.com/v/" + videoID +
    "&enablejsapi=1&playerapiid=player1", "videoDiv", "480", "295", "8", null, null, params, atts);
    
	//Offline panel
	initPlayer(getVideoIdByURL($("#url" + 1).val()) + ".flv");
	
	//Create database which stores the downloaded playlist!!
	db = google.gears.factory.create('beta.database');
	db.open('database-test');
	db.execute('create table if not exists Test' + ' (Phrase text)');
	updateList();
}

function _run(){
    loadPlayer();
}

function ytPlay(){
    currentURL = 1;
    var inputURL = $("#url" + currentURL).val();
    videoID = getVideoIdByURL(inputURL);
    ytplayer.loadVideoById(videoID, 0);
}

function getVideoIdByURL(iURL){
    var begin = iURL.indexOf("watch?v=") + 8;
    var end = begin + 11;
    return iURL.substring(begin, end);
}

function ytPlayNextOne(){
    currentURL++;
    var inputURL = $("#url" + currentURL).val();
    if (inputURL) {
        videoID = getVideoIdByURL(inputURL);
    }
    else {
        currentURL = 1;
        inputURL = $("#url" + currentURL).val();
        videoID = getVideoIdByURL(inputURL);
    }
    ytplayer.loadVideoById(videoID, 0);
}

function playerOfflineOnloadCallback(){
    playerOffline = document.getElementById("videoDivOffline");
}

function deletePlayer(theWrapper, thePlaceholder, thePlayerId) { 
        swfobject.removeSWF(thePlayerId);
        var tmp=document.getElementById(theWrapper);
        if (tmp) { tmp.innerHTML = "<div id=" + thePlaceholder + "></div>"; }
}
 
 
function createPlayer(thePlaceholder, thePlayerId, theFile, autoStart) {
		var swfUrl = "player-viral.swf";
        var flashvars = {
                file:theFile, 
				Image:"../preview.jpg",
                autostart:autoStart
        }
        var params = {
                allowfullscreen:"true", 
                allowscriptaccess:"always"
        }
        var attributes = {
                id:thePlayerId,  
                name:thePlayerId
        }
        swfobject.embedSWF(swfUrl, thePlaceholder, "500", "300", "9.0.115", false, flashvars, params, attributes);
		//alert("x");
}
 
 
function initPlayer(theFile) { 
        deletePlayer('YtPanelOffline', 'videoDivOffline', 'player1'); 
        createPlayer('videoDivOffline', 'player1', theFile, false);
}
function initPlayer(theFile,autoStart){
		deletePlayer('YtPanelOffline', 'videoDivOffline', 'player1'); 
        createPlayer('videoDivOffline', 'player1', theFile, autoStart);
		//
}
function selection(){
	if($("#playlist").html()=="<option>You didn't download any yet!!</option>")
		return;
	updateList();
}
function chosed(){
	//alert($("#playlist").val());
	initPlayer($("#playlist").val(),true);
}
function updateList(){
	var rs = db.execute('select * from Test');
	var list = "<option>Please select a downloaded file</option>";
	while(rs.isValidRow()){
		list = list + "<option>"+rs.field(0)+"</option>";
		rs.next();
	}
	$("#playlist").html(list);
}
